using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.Serialization;

public class WaterGun : MonoBehaviour
{
    [SerializeField] private GameObject _spray_0;
    [SerializeField] private GameObject _spray_1;

    private bool _isVertical;
    private SprayAngle _sprayAngle;
    public Transform _sprayPos;

    public void Init()
    {
        SetSprayType(SprayAngle.Angle_0);
        SetSprayActive(false);
        RotateNozzle(false);

        _sprayPos = transform.Find("SprayPos");
    }

    public void SetSprayType(SprayAngle sprayAngle)
    {
        _sprayAngle = sprayAngle;

        switch (sprayAngle)
        {
            case SprayAngle.Angle_0:
                ResetSprayRotate();
                break;
            case SprayAngle.Angle_10:
                _spray_1.transform.localScale = new Vector3(0.3f, 1, 1);
                break;
            case SprayAngle.Angle_20:
                _spray_1.transform.localScale = new Vector3(0.6f, 1, 1);
                break;
            case SprayAngle.Angle_30:
                _spray_1.transform.localScale = new Vector3(1, 1, 1);
                break;
        }
    }

    public void SetSprayActive(bool isActive)
    {
        switch (_sprayAngle)
        {
            case SprayAngle.Angle_0:
                _spray_0.gameObject.SetActive(isActive);
                _spray_1.gameObject.SetActive(false);
                break;
            default:
                if (isActive) DoShake();
                else StopShake();
                _spray_0.gameObject.SetActive(false);
                _spray_1.gameObject.SetActive(isActive);
                break;
        }
    }

    public void RotateNozzle(bool isVertical)
    {
        _sprayPos.transform.DOKill();
        if (_sprayAngle != SprayAngle.Angle_0)
        {
            _isVertical = isVertical;
            _sprayPos.transform.DOLocalRotate(new Vector3(0, 0, isVertical ? 90 : 0), 0.2f);
        }
        else
        {
            _sprayPos.transform.localEulerAngles = Vector3.zero;
        }
    }

    public void DoShake()
    {
        StopShake();
        Vector3 shakeDir = _isVertical ? Vector3.right : Vector3.up;
        _sprayPos.DOShakeRotation(0.01f, shakeDir * 3f, 0, 150, false).SetLoops(-1);
    }

    private void StopShake()
    {
        _sprayPos.DOKill();
    }

    private void ResetSprayRotate() => _sprayPos.localRotation = Quaternion.identity;

    public enum SprayAngle
    {
        Angle_0,
        Angle_10,
        Angle_20,
        Angle_30
    }
}